<?php

namespace App\Http\Controllers\Note;

use App\Http\Controllers\Controller;
use App\Models\Note\Tag;
use App\Models\Note\Doc;
use Illuminate\Http\Request;

class TagController extends Controller
{
    public function index()
    {
        $obj = Tag::orderBy('total', 'desc')->get();
        return $this->response($obj);
    }

    public function update()
    {
        $list = Doc::pluck('tags');
        Tag::where('id', '>', 0)->delete();
        $data = [];
        foreach ($list as $tags) {
            foreach ($tags as $tag) {
                if (isset($data[$tag])) {
                    $data[$tag] = $data[$tag] + 1;
                } else {
                    $data[$tag] = 1;
                }
            }
        }
        $arr = [];
        foreach ($data as $k => $v) {
            $arr[] = ['title' => $k, 'total' => $v];
        }
        Tag::insert($arr);
        return $this->index();
    }
}
